﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Torch_Services
{
    public class UsersService : IUsersService
    {
        private IUsersDal _users;
        private IMapper _mapper;
        public UsersService(IUsersDal users, IMapper mapper)
        {
            _users = users;
            _mapper = mapper;
        }

        public async Task<int> AddUserAsync(string account, string password, int roleId)
        {
            return await _users.AddAsync(new User 
            {
                Account = account,
                Password = password,
                Rid = roleId
            });
        }

        public async Task<int> DeleteUserAsync(int id)
        {
            var data = await _users.QueryAsync(id);
            return data == null ? -1 : await _users.DeleteAsync(data);
        }

        public async Task<int> EditUserAsync(int id, string password)
        {
            var data = await _users.QueryAsync(id);
            if (data == null)
                return -1;
            data.Password = password;
            return await _users.EditAsync(data);
        }

        public async Task<UsersDto> LoginAsync(string account, string password)
        {
            var data = await _users.QueryAsync(user => user.Account.Equals(account) && user.Password.Equals(password));
            return data == null || data.Count == 0 ? null : new UsersDto 
            {
                Id = data[0].Id,
                Rid = data[0].Rid
            };
        }

        public async Task<List<UsersDto>> QueryUserAllAsync()
        {
            var data = await _users.QueryAsync();
            return _mapper.Map<List<User>, List<UsersDto>>(data);
        }

        public async Task<List<UsersDto>> QueryUserByAccountAsync(string account)
        {
            var data = await _users.QueryAsync(u => u.Account.Equals(account));
            return _mapper.Map<List<User>,List<UsersDto>>(data);
        }

    }
}
